/**
 * promise.all() 和 promise.race
 */

const ajaxQuery = (url) => {
  return new Promise((resolve, reject) => {
    const http = new XMLHttpRequest();
    http.open("GET", url);
    http.responseType = "json";
    http.onload = function () {
      setTimeout(() => {
        if (this.status === 200) {
          resolve(this.response);
        } else {
          reject(new Error(this.statusText));
        }
      }, 2000);
    };
    http.send();
  });
};

ajaxQuery("/04-test/posts.json")
  .then((res) => {
    console.log(res);
    const urls = Object.values(res);
    const ajaxs = urls.map((o) => ajaxQuery(o));
    return Promise.all(ajaxs);
  })
  .then((res) => {
    console.log(res);
    const promise = ajaxQuery("/04-test/data.json");
    const promise2 = ajaxQuery("/04-test/data2.json");
    return Promise.race([promise, promise2]);
  })
  .then((res) => {
    console.log(res);
  });
